package portal.manager.tracker;

import java.util.logging.Logger;

import org.jabsorb.JSONRPCBridge;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;

/**
 * 
 * @author Sorrentino
 *
 */
public class JSONServiceTracker extends ServiceTracker {

	
	/**
	 * 
	 * @param context
	 * @return
	 * @throws Exception
	 */
	static public ServiceTracker createJSONServiceTracker( BundleContext context ) throws Exception {
		final String assertMsg = "param context is null!";
		
		assert null!=context: assertMsg;
		
		if( null==context ) throw new IllegalArgumentException(assertMsg);
		
		Filter filter = context.createFilter("(bind.protocol=json-rpc)");
		
		return new JSONServiceTracker( context, filter, null );
	}

	/**
	 * 
	 * @param context
	 * @param filter
	 * @param customizer
	 */
	private JSONServiceTracker(BundleContext context, Filter filter,
			ServiceTrackerCustomizer customizer) {
		super(context, filter, customizer);
	}

	private String getProxyName( ServiceReference reference, Object service ) {

		String proxyName = (String)reference.getProperty("bind.name");
		
		if( null==proxyName ) {
			String className = service.getClass().getName();
			int idx = className.lastIndexOf('.');
			proxyName = ( idx!=-1 ) ? className.substring(++idx) : className; 
		}
		
		return proxyName;
	}

	@Override
	public Object addingService(ServiceReference reference) {
		
		Object service = super.addingService(reference);

		String proxyName = getProxyName( reference, service );
		
		System.out.printf( "registering json-rpc service bind.name=%s class=%s ....", proxyName, service.getClass().getName());
		JSONRPCBridge.getGlobalBridge().registerObject( proxyName, service );
		System.out.printf( "done!\n");
		
		return service; 
	}

	@Override
	public void removedService(ServiceReference reference, Object service) {

		Logger.global.entering(getClass().getName(), "ungetService");

		String proxyName = getProxyName( reference, service );
		
		JSONRPCBridge.getGlobalBridge().unregisterObject(proxyName);
	}

}
